<template>
  <div ref="pdfContainer" class="pdf-container">
    <canvas v-for="(page, index) in pages" :key="index" :ref="`pdfPage${index}`"></canvas>
  </div>
</template>
<!-- import pdfViewer from '@/components/pdf' -->
<script>
import { ref, onMounted, watch } from 'vue';
import * as pdfjsLib from 'pdfjs-dist';
import 'pdfjs-dist/web/pdf_viewer.css';

pdfjsLib.GlobalWorkerOptions.workerSrc = new URL(
  'pdfjs-dist/build/pdf.worker.min.js',
  import.meta.url
).toString();

export default {
  props: {
    url: {
      type: String,
      required: true
    }
  },
  setup (props) {
    const pdfContainer = ref(null);
    const pages = ref([]);

    watch(() => props.url, async () => {
      console.log('watch-------')
      console.log(props.url)

      const loadingTask = pdfjsLib.getDocument(props.url);
      const pdf = await loadingTask.promise;

      for (let i = 1; i <= pdf.numPages; i++) {
        const page = await pdf.getPage(i);
        const viewport = page.getViewport({ scale: 1.5 });
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        const renderContext = {
          canvasContext: context,
          viewport: viewport
        };

        await page.render(renderContext).promise;
        pages.value.push(canvas);
      }

      // Append canvases to the container
      pages.value.forEach((canvas, index) => {
        const canvasRef = pdfContainer.value.querySelector(`#pdfPage${index}`);
        if (canvasRef) {
          canvasRef.appendChild(canvas);
        }
      });

    });

    onMounted(async () => {
      console.log('onMounted-------')
      console.log(props.url)
      const loadingTask = pdfjsLib.getDocument(props.url);
      const pdf = await loadingTask.promise;

      for (let i = 1; i <= pdf.numPages; i++) {
        const page = await pdf.getPage(i);
        const viewport = page.getViewport({ scale: 1.5 });
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        const renderContext = {
          canvasContext: context,
          viewport: viewport
        };

        await page.render(renderContext).promise;
        pages.value.push(canvas);
      }

      // Append canvases to the container
      pages.value.forEach((canvas, index) => {
        const canvasRef = pdfContainer.value.querySelector(`#pdfPage${index}`);
        if (canvasRef) {
          canvasRef.appendChild(canvas);
        }
      });

    });

    return {
      pdfContainer,
      pages
    };
  }
};
</script>

<style scoped>
.pdf-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  height: 100%;
  overflow-y: auto;
}

canvas {
  margin: 10px 0;
}
</style>